package com.ymttest.business.data;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymatou.iapi.productquery.parameter.ProductDetail.ProductInDetailBean;
import com.ymatou.iapi.productquery.service.GetProductInfoByProductIdCall;
import com.ymatou.iapi.selleractivity.service.ApplyActivityCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.AdminCallService;
import com.ymttest.business.service.JUserCallService;
import com.ymttest.business.service.ProductManagerCallServiceV2;
import com.ymttest.business.service.ProductManagerCallServiceV3;
import com.ymttest.business.service.ProductQueryCallService;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

/************************************************************************************
 * @File name :Data201811.java
 * @Author : zhouyi
 * @Date : 2019年8月6日
 * @Copyright : 洋码头
 * stg压测用
 ************************************************************************************/
public class Data201811 {
	// 日志
	private static String logfile = "stgcreateproduct.log";
	// 活动id 固定 activityId 7887
//	private static String activityId = "7887";
//	private static String IsolationactivityId = "7913";
	private static String adminuser = "zhouyi";
	private static String adminpwd = "1234qwer";
//	8102  低权重活动  
//	8101  高权重活动
//	private static String h_activityId = "8265";
//	private static String l_activityId = "8266";

	/**
	 * 创建商品
	 * 
	 * @param data
	 *            sellerid sellername
	 * @param pnum
	 *            创建数量
	 * @return
	 * @throws Exception
	 */
	public static List<Map> createProducts(Integer sellerId, String sellerName, Integer pnum, boolean isIsolation) throws Exception {
		List<Map> mpids = new ArrayList<Map>();

		// 创建商品限制
		// SELECT TOP 1000 [ID]
		// ,[SellerID]
		// ,[ProductPits]
		// ,[CreateTime]
		// ,[LastUpdateTime]
		// FROM [YmtSellerReport].[dbo].[ymt_sellerproductpits] where
		// sellerid=21159026
		Logger.debug("创建商品");
//		AddSellerProductRequest addSellerProductRequest = ProductManagerCallServiceV3.initAddSellerProductRequest(3383);
//		String productId = ProductManagerCallServiceV3.AddSellerProduct(addSellerProductRequest);
		for (int i = 0; i < pnum; i++) {
			String productId;
			if (isIsolation) {
				productId = ProductManagerCallServiceV2.getStgOneProductId(sellerName, sellerId, 999999);
			} else {
				Calendar c = Calendar.getInstance();
				c.add(Calendar.HOUR_OF_DAY, 8);
				productId = ProductManagerCallServiceV2.getStgProductId(sellerName, sellerId, 999999,c);
			}
			Thread.sleep(2000);
			Map map = new HashMap<>();
			map.put("productId", productId);
			map.put("sellerId", sellerId);
			map.put("sellerName", sellerName);
			mpids.add(map);
		}
		mpids.forEach(map2 -> {

			String productId = map2.get("productId").toString();
			Logger.debug("查询商品");
			JSONObject prodDetail = new GetProductInfoByProductIdCall().callAndGetReturnData(productId);

			ProductInDetailBean prodBean = null;
			List<String> catalogList = new ArrayList<>() ;
			try {
				prodBean = ProductQueryCallService.getBeanFromJson(prodDetail.getJSONObject("Data").getJSONObject("Product"), ProductInDetailBean.class);
				catalogList=prodBean.getCatalogList().stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
			} catch (Throwable e) {
				try {
					Thread.sleep(1000);
					prodBean = ProductQueryCallService.getBeanFromJson(prodDetail.getJSONObject("Data").getJSONObject("Product"), ProductInDetailBean.class);
					catalogList=prodBean.getCatalogList().stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				
			}
			 

			for (String catalog : catalogList) {
				TestDataManager.appendFileToLine(logfile, sellerId + ":" + productId + ":" + catalog);
			}

			// TestDataManager.appendFileToLine(logfile, sellerId + ":创建商品:" +
			// productId + ":catalogList:" + catalogList);
			map2.put("catalogList", catalogList);
		});
		return mpids;
	}

//	public static List<Map> getProducts(Integer sellerId, String sellerName) throws Exception {
//		List<Map> mpids = new ArrayList<Map>();
//		List<String> alllist = ProductManagerCallServiceV2.getAllOnSaleProducts(sellerId);
//		for (String productId : alllist) {
//			JSONObject prodDetail = new GetProductInfoByProductIdCall().callAndGetReturnData(productId);
//			ProductInDetailBean prodBean = ProductQueryCallService.getBeanFromJson(prodDetail.getJSONObject("Data").getJSONObject("Product"), ProductInDetailBean.class);
//			Logger.debug(FormatUtil.beanToGSONString(prodBean));
//
//			if (prodBean.getCatalogList().size() == 10 && prodBean.getCatalogList().get(0).getPrice().equals(10d)) {
//
//				List<String> catalogList = prodBean.getCatalogList().stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
//
//				for (String catalog : catalogList) {
//					TestDataManager.appendFileToLine(logfile, sellerId + ":" + productId + ":" + catalog);
//				}
//				//
//				TestDataManager.appendFileToLine(logfile, sellerId + ":" + productId + ":" + catalogList.get(0));
//
//				Map map = new HashMap<>();
//				map.put("productId", productId);
//				map.put("sellerId", sellerId);
//				map.put("sellerName", sellerName);
//				map.put("catalogList", catalogList);
//				mpids.add(map);
//			}
//		}
//		return mpids;
//	}

//	/**
//	 * 报名审核活动
//	 * List<productId sellerId sellerName catalogList>
//	 * @throws Exception
//	 */
//	public static void addActivity(List<Map> mpids) throws Exception {
//		Logger.debug("报名活动");
//		for (Map map : mpids) {
//			String productId = map.get("productId").toString();
//			Integer sellerId = Integer.valueOf(map.get("sellerId").toString());
//			String sellerName = map.get("sellerName").toString();
//			List<String> catalogList = (List<String>) map.get("catalogList");
//
//			ApplyActivityCall activityCall = new ApplyActivityCall();
//			JSONObject applyEffectiveActBean = activityCall.getJsonBean(null);
//			String applyMsg = "";
//			Map<String, Object> requestMap = new HashMap<String, Object>();
//			requestMap.put("SellerId", sellerId);
//			requestMap.put("ActivityId", activityId);
//			requestMap.put("ActivityProducts[0]->ProductId", productId);
//			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->CatalogId",
//			// catalogList.get(0));
//			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->ActivityStockNum",
//			// 90000);
//			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->ActivityPrice",
//			// 10);
//			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->Sku", "");
//			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->BkcKey",
//			// "");
//			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->ProductInActivityId",
//			// 0);
//
//			for (int i = 0; i < catalogList.size(); i++) {
//				JSONArray CatalogListBean = applyEffectiveActBean.getJSONArray("ActivityProducts").getJSONObject(0).getJSONArray("ApplyCatalogs");
//				CatalogListBean.put(i, new JSONObject(CatalogListBean.get(0).toString()));
//				CatalogListBean.getJSONObject(i).put("CatalogId", catalogList.get(i));
//				CatalogListBean.getJSONObject(i).put("ActivityStockNum", 90000);
//				CatalogListBean.getJSONObject(i).put("ActivityPrice", 10);
//				CatalogListBean.getJSONObject(i).put("Sku", "");
//				CatalogListBean.getJSONObject(i).put("BkcKey", "");
//				CatalogListBean.getJSONObject(i).put("ProductInActivityId", 0);
//			}
//
//			JsonBeanHelper.updateJsonBean(applyEffectiveActBean, requestMap);
//
//			activityCall.setData(applyEffectiveActBean);
//			Logger.debug("报名");
//			activityCall.callService();
//			JSONObject ret = new JSONObject(activityCall.getReturnData());
//			applyMsg = activityCall.getReturnData();
//			// TestDataManager.appendFileToLine(logfile, "catalogList[0]:" +
//			// catalogList.get(0) + ":报名活动:" + applyMsg);
//			if (ret.has("Data") && ret.getJSONObject("Data").has("ApplySuccessProducts") && ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").length() > 0) {
//				JSONArray aslist = ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts");
//				for (int i = 0; i < aslist.length(); i++) {
//					String inaid = aslist.getJSONObject(i).getString("ProductInActivityId");
//					JSONObject jo = AdminCallService.approveProductInActivity(adminuser, adminpwd, inaid,
//							MapUtil.hashMap("productBeginTime", YMTDateUtil.getBeforeOrNextSecond(300), "productEndTime", YMTDateUtil.getBeforeOrNextSecond(10 * 60 * 60 * 24)));
//					String msgSuccess = "product: " + productId + ",inaid:" + inaid;
//					Logger.debug("审核:" + msgSuccess);
//				}
//				// String inaid =
//				// ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").getJSONObject(0).getString("ProductInActivityId");
//				// JSONObject jo =
//				// AdminCallService.approveProductInActivity(adminuser,
//				// adminpwd, inaid,
//				// MapUtil.hashMap("productBeginTime",
//				// YMTDateUtil.getBeforeOrNextSecond(300), "productEndTime",
//				// YMTDateUtil.getBeforeOrNextSecond(10*60*60*24)));
//				//
//				// String msgSuccess = "product: " + productId + ",inaid:" +
//				// inaid;
//				//
//				//// TestDataManager.appendFileToLine(logfile, "审核:" +
//				// msgSuccess);
//				// Logger.debug("审核:" + msgSuccess);
//			}
//		}
//
//	}
//
//	/**
//	 * 报名审核活动
//	 * 
//	 * @throws Exception
//	 */
//	public static void addIsolationActivity(List<Map> mpids) throws Exception {
//		Logger.debug("报名交易隔离活动");
//		for (Map map : mpids) {
//			String productId = map.get("productId").toString();
//			Integer sellerId = Integer.valueOf(map.get("sellerId").toString());
//			String sellerName = map.get("sellerName").toString();
//			List<String> catalogList = (List<String>) map.get("catalogList");
//
//			ApplyActivityCall activityCall = new ApplyActivityCall();
//			JSONObject applyEffectiveActBean = activityCall.getJsonBean(null);
//			String applyMsg = "";
//			Map<String, Object> requestMap = new HashMap<String, Object>();
//			requestMap.put("SellerId", sellerId);
//			requestMap.put("ActivityId", IsolationactivityId);
//			requestMap.put("ActivityProducts[0]->ProductId", productId);
//
//			for (int i = 0; i < 1; i++) {
//				JSONArray CatalogListBean = applyEffectiveActBean.getJSONArray("ActivityProducts").getJSONObject(0).getJSONArray("ApplyCatalogs");
//				CatalogListBean.put(i, new JSONObject(CatalogListBean.get(0).toString()));
//				CatalogListBean.getJSONObject(i).put("CatalogId", catalogList.get(i));
//				CatalogListBean.getJSONObject(i).put("ActivityStockNum", 90000);
//				CatalogListBean.getJSONObject(i).put("ActivityPrice", 10);
//				CatalogListBean.getJSONObject(i).put("Sku", "");
//				CatalogListBean.getJSONObject(i).put("BkcKey", "");
//				CatalogListBean.getJSONObject(i).put("ProductInActivityId", 0);
//			}
//
//			JsonBeanHelper.updateJsonBean(applyEffectiveActBean, requestMap);
//
//			activityCall.setData(applyEffectiveActBean);
//			Logger.debug("报名");
//			activityCall.callService();
//			JSONObject ret = new JSONObject(activityCall.getReturnData());
//			applyMsg = activityCall.getReturnData();
//			// TestDataManager.appendFileToLine(logfile, "catalogList[0]:" +
//			// catalogList.get(0) + ":报名活动:" + applyMsg);
//			if (ret.has("Data") && ret.getJSONObject("Data").has("ApplySuccessProducts") && ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").length() > 0) {
//				JSONArray aslist = ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts");
//				for (int i = 0; i < aslist.length(); i++) {
//					String inaid = aslist.getJSONObject(i).getString("ProductInActivityId");
//					JSONObject jo = AdminCallService.approveProductInActivity(adminuser, adminpwd, inaid,
//							MapUtil.hashMap("productBeginTime", YMTDateUtil.getBeforeOrNextSecond(300), "productEndTime", YMTDateUtil.getBeforeOrNextSecond(10 * 60 * 60 * 24)));
//					String msgSuccess = "product: " + productId + ",inaid:" + inaid;
//					Logger.debug("审核:" + msgSuccess);
//				}
//				// String inaid =
//				// ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").getJSONObject(0).getString("ProductInActivityId");
//				// JSONObject jo =
//				// AdminCallService.approveProductInActivity(adminuser,
//				// adminpwd, inaid,
//				// MapUtil.hashMap("productBeginTime",
//				// YMTDateUtil.getBeforeOrNextSecond(300), "productEndTime",
//				// YMTDateUtil.getBeforeOrNextSecond(10*60*60*24)));
//				//
//				// String msgSuccess = "product: " + productId + ",inaid:" +
//				// inaid;
//				//
//				//// TestDataManager.appendFileToLine(logfile, "审核:" +
//				// msgSuccess);
//				// Logger.debug("审核:" + msgSuccess);
//			}
//		}
//
//	}
	/**
	 * 报名活动 用于参数多活动场景
	 * @param mpids
	 * @param aid
	 * @throws Exception
	 */
	public static void addTActivity(List<Map> mpids,String aid,Double aprice) throws Exception {
		Logger.debug("报名交易隔离活动:"+aid);
		for (Map map : mpids) {
			String productId = map.get("productId").toString();
			Integer sellerId = Integer.valueOf(map.get("sellerId").toString());
			String sellerName = map.get("sellerName").toString();
			List<String> catalogList = (List<String>) map.get("catalogList");

			ApplyActivityCall activityCall = new ApplyActivityCall();
			JSONObject applyEffectiveActBean = activityCall.getJsonBean(null);
			String applyMsg = "";
			Map<String, Object> requestMap = new HashMap<String, Object>();
			requestMap.put("SellerId", sellerId);
			requestMap.put("ActivityId", aid);
			requestMap.put("ProductNameInActivity", "活动商品B");
			requestMap.put("ActivityProducts[0]->ProductNameInActivity", "活动商品B");
			requestMap.put("ActivityProducts[0]->ProductId", productId);
//MarketPrice
			requestMap.put("ActivityProducts[0]->MarketPrice", aprice+1);
			for (int i = 0; i < catalogList.size(); i++) {
				JSONArray CatalogListBean = applyEffectiveActBean.getJSONArray("ActivityProducts").getJSONObject(0).getJSONArray("ApplyCatalogs");
				CatalogListBean.put(i, new JSONObject(CatalogListBean.get(0).toString()));
				CatalogListBean.getJSONObject(i).put("CatalogId", catalogList.get(i));
				CatalogListBean.getJSONObject(i).put("ActivityStockNum", 90000);
				CatalogListBean.getJSONObject(i).put("ActivityPrice", aprice);
				CatalogListBean.getJSONObject(i).put("Sku", "");
				CatalogListBean.getJSONObject(i).put("BkcKey", "");
				CatalogListBean.getJSONObject(i).put("ProductInActivityId", 0);
			}

			JsonBeanHelper.updateJsonBean(applyEffectiveActBean, requestMap);

			activityCall.setData(applyEffectiveActBean);
			Logger.debug("报名");
			activityCall.callService();
			JSONObject ret = new JSONObject(activityCall.getReturnData());
			applyMsg = activityCall.getReturnData();
			// TestDataManager.appendFileToLine(logfile, "catalogList[0]:" +
			// catalogList.get(0) + ":报名活动:" + applyMsg);
			if (ret.has("Data") && ret.getJSONObject("Data").has("ApplySuccessProducts") && ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").length() > 0) {
				JSONArray aslist = ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts");
				for (int i = 0; i < aslist.length(); i++) {
					String inaid = aslist.getJSONObject(i).getString("ProductInActivityId");
					//高优先级活动时间不能超过24h
					JSONObject jo = AdminCallService.approveProductInActivity(adminuser, adminpwd, inaid,
							MapUtil.hashMap("productBeginTime", YMTDateUtil.getBeforeOrNextSecond(-30), "productEndTime", YMTDateUtil.getBeforeOrNextSecond( 60 * 60 * 24-31)));
					String msgSuccess = "product: " + productId + ",inaid:" + inaid;
					Logger.debug("审核:" + msgSuccess);
				}
			}
		}

	}
	public static List<Map> getProducts(Integer sellerId, String sellerName) throws Exception {
		List<Map> mpids = new ArrayList<Map>();
		List<String> alllist = ProductManagerCallServiceV2.getAllOnSaleProducts(sellerId);
		for (String productId : alllist) {
			JSONObject prodDetail = new GetProductInfoByProductIdCall().callAndGetReturnData(productId);
			ProductInDetailBean prodBean = ProductQueryCallService.getBeanFromJson(prodDetail.getJSONObject("Data").getJSONObject("Product"), ProductInDetailBean.class);
			Logger.debug(FormatUtil.beanToGSONString(prodBean));

			if (prodBean.getCatalogList().size() == 1 && prodBean.getCatalogList().get(0).getPrice().equals(10d)) {

				List<String> catalogList = prodBean.getCatalogList().stream().map(x -> x.getCatalogId()).collect(Collectors.toList());

				for (String catalog : catalogList) {
					TestDataManager.appendFileToLine(logfile, sellerId + ":" + productId + ":" + catalog);
				}
				//
				TestDataManager.appendFileToLine(logfile, sellerId + ":" + productId + ":" + catalogList.get(0));

				Map map = new HashMap<>();
				map.put("productId", productId);
				map.put("sellerId", sellerId);
				map.put("sellerName", sellerName);
				map.put("catalogList", catalogList);
				mpids.add(map);
			}
		}
		return mpids;
	}
	/**
	 * 创建商品并加入活动 高低优先级活动同时发生
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		
		// 商品数
		int pnum =100;
		List<String> list = TestDataManager.getLines("data");
		Integer price=5000;
		ProductManagerCallServiceV3.BrandId=26411;
		for (String datas : list) {
			Integer sellerId = Integer.valueOf(datas.split(" ")[0]);
			String sellerName = datas.split(" ")[1];
			// List<Map> mpids =
			//创建商品
			ProductManagerCallServiceV2.price=price.toString();
			List<Map> mpids = Data201811.createProducts(sellerId, sellerName, pnum,true);
//			 Thread.sleep(10000);
//			 List<Map> mpids = Data201811.getProducts(sellerId, sellerName);
//			 Logger.debug(mpids);
//			// 下架
//			 for (Map map : mpids) {
//			 String productId=map.get("productId").toString();
//			 List<String> pids=new ArrayList<>();
//			 pids.add(productId);
//			 ProductManagerCallServiceV2.batchSetProductOffSale(pids,sellerId);
//			 }
//			参加活动
			try{
//				Data201811.addTActivity(mpids,"8738",Double.valueOf(price));
//				Data201811.addTActivity(mpids,Data201811.h_activityId);
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
}
